package cn.aiyuan.service.impl;

import cn.aiyuan.query.UserQuery;
import cn.aiyuan.dao.UserDao;
import cn.aiyuan.pojo.User;
import cn.aiyuan.service.IUserService;
import com.github.wenhao.jpa.Specifications;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

/**
 * @author wy
 * @since 2020/7/6
 */
@Service
public class UserServiceImpl  implements IUserService {

    @Autowired
    private UserDao userDao;



    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }

    @Override
    public void insert(User user) {
        userDao.save(user);
    }

    @Override
    public void updateById(User user) {
        userDao.save(user);
    }

    @Override
    public Page<User> findByCondition(UserQuery userQuery) {
        PageRequest pageRequest =
                PageRequest.of(userQuery.getJpaPageNo(), userQuery.getSize(),Sort.by(Sort.Direction.DESC,"id"));
        System.out.println("pageRequest.toString() = " + pageRequest.toString());
        Specification<User> build =
                Specifications.<User>and()
                        .like(StringUtils.hasLength(userQuery.getKeyWord()),"nickname","%"+userQuery.getKeyWord()+"%")
                        .build();
        return userDao.findAll(build, pageRequest);
    }

    @Override
    public void deleteById(Long id) {
        userDao.deleteById(id);
    }

    @Override
    public Optional<User> findOneById(Long id) {
        return userDao.findById(id);
    }


}
